/**
 * @file 主进程全局状态管理模块
 * @description 实现主进程中的全局持久化状态管理，支持主进程和渲染进程之间的状态同步
 * 提供IPC通信、状态存储、多进程同步等核心功能
 * @author 黄敏
 * @created 2025-06-16 19:38
 * @updated 2025-01-27 优化注释和文档，移除冗余示例
 */

import { ipcMain } from 'electron'
import { topic } from '../common/config'
import { CreateState, type StoreOptions } from './create-storage-state'

export  { CreateState }

/**
 * 处理获取状态请求
 * @description 响应渲染进程的状态获取请求，支持获取完整状态或特定键值
 *
 * @param event - IPC事件对象
 * @param key - 可选的特定键名
 */
ipcMain.on(
  topic.get,
  (
    event,
    name: string,
    opitions?: {
      defaults: Record<string, unknown>
      version: number
      options?: StoreOptions
    }
  ) => {
    try {
      let stores: CreateState<Record<string, unknown>> | undefined
      if (opitions) {
        stores = new CreateState(name, opitions.defaults, opitions.version, opitions.options)
      } else {
        stores = CreateState.instances.get(name)
      }

      if (stores) {
        event.returnValue = stores.getByRenderer(event.sender.id)
      } else {
        event.returnValue = null
      }
    } catch (error) {
      console.error(`[GlobalState:${name}] Failed to get state:`, error)
      event.returnValue = null
    }
  }
)

/**
 * 处理设置状态请求
 * @description 响应渲染进程的状态设置请求，支持设置完整状态或特定键值
 *
 * @param event - IPC事件对象
 * @param data - 要设置的状态数据
 * @param key - 可选的特定键名
 */
ipcMain.on(
  topic.set,
  <Data extends Record<string, unknown>, Key extends keyof Data>(
    _: unknown,
    name: string,
    data: Data | Data[Key],
    key?: string
  ) => {
    try {
      const stores = CreateState.instances.get(name)

      if (stores) {
        stores.setByRenderer(name, data, key)
      }
    } catch (error) {
      console.error(`[全局状态:${name}] 设置状态失败:`, error)
    }
  }
)

export const createStorageState = <T extends Record<string, unknown>>(
  name: string,
  defaults: T,
  version: number,
  options?: StoreOptions
) => {
  return new CreateState(name, defaults, version, options)
}
